package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminBrands.*;
import com.shop.entity.pojo.AdminUser;
import com.shop.entity.pojo.Brands;
import com.shop.entity.pojo.Wares;
import com.shop.admin.mapper.AdminUserMapper;
import com.shop.admin.mapper.BrandsMapper;
import com.shop.admin.mapper.WaresMapper;
import com.shop.admin.service.BrandsService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BrandsServiceImpl extends ServiceImpl<BrandsMapper, Brands> implements BrandsService {

    @Autowired
    private BrandsMapper brandsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result getWaresBrandsList(AdminBrandsListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-分类列表");
        dto.checkParam();
        Page<Brands> page=new Page(dto.getPage(),dto.getSize());
        String key=Message.WeChat_Key_Brands_All;
        Page<Brands> check = (Page<Brands>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理获取分类列表进程完成，总耗时:{}",(end-start));
            return result;
        }
        log.info("浏览数据库");
        Page<Brands> value = brandsMapper.getAllByPage(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理获取分类列表进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Override
    public Result saveWaresBrands(AdminBrandsSaveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-添加商品分类");
        if (dto==null||dto.getBrandsName()==null) {
            log.info("缺少前端传来的添加参数");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            log.info("未查询到该管理员身份");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        List<Brands> brandslist = brandsMapper.selectList(Wrappers.<Brands>lambdaQuery().eq(Brands::getBrandsName, dto.getBrandsName()));
        if (!CollectionUtils.isEmpty(brandslist)||brandslist.size()>Message.Check_Int_Null) {
            log.info("该商品分类名已存在");
            return Result.errorResult(Code.DATA_EXIST);
        }
        Brands brands=new Brands();
        brands=brands.builder()
                .brandsName(dto.getBrandsName())
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int insert = brandsMapper.insert(brands);
        if (insert==Message.Check_Int_False) {
            log.info("添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理添加商品分类进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateGetWaresBrands(AdminBrandsUpdateForGetDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-商品分类修改回显");
        if (dto.getBrandsId()==null) {
            log.info("未接收到商品分类ID");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Brands brands = brandsMapper.selectById(dto.getBrandsId());
        if (brands==null) {
            log.info("未查询到该商品分类");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品分类数据回显进程完成，总耗时:{}",(end-start));
        return Result.okResult(brands);
    }

    @Override
    public Result updateWaresBrands(AdminBrandsUpdateDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-商品修改");
        if (dto==null||dto.getBrandsId()==null||dto.getBrandsName()==null) {
            log.info("未查询到前端传来的json数据或有缺失数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Brands oldBrands = brandsMapper.selectById(dto.getBrandsId());
        if (oldBrands==null||oldBrands.getBrandsName().equals(dto.getBrandsName())) {
            log.info("未查询到该商品分类");
            log.info("商品分类名需要变化");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Brands> brandsList = brandsMapper.selectList(Wrappers.<Brands>lambdaQuery().eq(Brands::getBrandsName, dto.getBrandsName()));
        if (!CollectionUtils.isEmpty(brandsList)||brandsList.size()>Message.Check_Int_Null) {
            log.info("该商品分类已存在");
            log.info("brandsList:{}",brandsList);
            log.info("size:{}",brandsList.size());
            return Result.errorResult(Code.DATA_EXIST);
        }
        Brands brands=new Brands();
        brands=brands.builder()
                .brandsName(dto.getBrandsName())
                .saveAdmin(adminUser.getName()).build();
        int update = brandsMapper.update(brands, Wrappers.<Brands>lambdaUpdate().eq(Brands::getId, dto.getBrandsId()));
        if (update==Message.Check_Int_False) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品分类进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Autowired
    private WaresMapper waresMapper;
    @Override
    public Result removeWaresBrands(AdminBrandsRemoveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-删除商品分类");
        if (dto==null||dto.getBrandsId()==null||dto.getRemoveMemo()==null) {
            log.info("未接收到必须传参的json数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Brands getBrands = brandsMapper.selectById(dto.getBrandsId());
        if (getBrands==null) {
            log.info("未查询到该商品分类");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Wares> waresList = waresMapper.selectList(Wrappers.<Wares>lambdaQuery().eq(Wares::getBrandsId, dto.getBrandsId()));
        if (!CollectionUtils.isEmpty(waresList)||waresList.size()>Message.Check_Int_Null) {
            log.info("该分类内仍有商品数据存在,请先删除商品数据");
            if (dto.getRemoveTureOrFalse().equals("false")) {
                return Result.errorResult(Code.SERVER_ERROR);
            }else if (dto.getRemoveTureOrFalse().equals("true")){
                Wares wares=new Wares();
                wares= wares.builder().removeAdmin(adminUser.getName()).removeMemo(dto.getRemoveMemo()).build();
                int update = waresMapper.update(wares, Wrappers.<Wares>lambdaQuery().eq(Wares::getBrandsId, dto.getBrandsId()));
                int delete = waresMapper.delete(Wrappers.<Wares>lambdaQuery().eq(Wares::getBrandsId, dto.getBrandsId()));
                if (update==Message.Check_Int_False||delete==Message.Check_Int_False) {
                    log.info("商品分类内的商品数据删除失败");
                }
            } else {
                log.info("无效参数");
                return Result.errorResult(Code.PARAM_INVALID);
            }
        }
        Brands brands=new Brands();
        brands=brands.builder()
                .removeAdmin(adminUser.getName())
                .removeMemo(dto.getRemoveMemo()).build();
        int update = brandsMapper.update(brands, Wrappers.<Brands>lambdaUpdate().eq(Brands::getId, dto.getBrandsId()));
        if (update==Message.Check_Int_False) {
            log.info("添加信息失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        int delete = brandsMapper.delete(Wrappers.<Brands>lambdaUpdate().eq(Brands::getId, dto.getBrandsId()));
        if (delete==Message.Check_Int_False) {
            log.info("删除商品分类失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理删除商品分类进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result openBrands(AdminBrandsOpenDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-恢复分类");
        if (dto.getBrandsId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Brands byId = brandsMapper.getById(dto.getBrandsId());
        if (adminId==null||adminUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }

        if (byId.getIsDelete()==Message.Delete_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        Brands brands=new Brands().builder()
                .id(dto.getBrandsId())
                .isDelete(Message.Put)
                .saveAdmin(adminUser.getName())
                .removeAdmin(null)
                .removeMemo(null)
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = brandsMapper.update(brands);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理恢复商品分类进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }
}
